import * as types from '../mutaion-types'
import {getLocalStorage, setLocalStorage, removeLocalStorage} from '../../lib/util'

const state = {
  loginStatus: getLocalStorage('loginStatus') || false,
  userInfo: JSON.parse(getLocalStorage('userInfo')) || {}
}

const getters = {
  getLoginStatus: state => state.loginStatus,
  getUserInfo: state => state.userInfo
}

const mutations = {
  [types.SET_USER_INFO] (state, user) {
    state.userInfo = user
  },
  [types.SET_USER_LOGIN_STATUS] (state, status) {
    state.loginStatus = status
  }
}

const actions = {
  userLoginAction ({commit}, user) {
    setLocalStorage('userInfo', JSON.stringify(user))
    setLocalStorage('loginStatus', true)
    commit(types.SET_USER_INFO, user)
    commit(types.SET_USER_LOGIN_STATUS, true)
  },
  userLoginOutAction ({commit}) {
    removeLocalStorage('userInfo')
    removeLocalStorage('loginStatus')
    commit(types.SET_USER_INFO, {})
    commit(types.SET_USER_LOGIN_STATUS, false)
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
